package com.example.c94s3plyhyfc.web;

import com.example.c94s3plyhyfc.bean.Result;
import com.example.c94s3plyhyfc.bean.User;
import com.example.c94s3plyhyfc.biz.BizException;
import com.example.c94s3plyhyfc.biz.MailServiceImpl;
import com.example.c94s3plyhyfc.biz.UserBiz;
import com.example.c94s3plyhyfc.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

@Controller
@SessionAttributes(value = {"loginedUser", "regVcode"}) // 监控Model出现的指定对象, 存入会话
// @SessionAttribute 从会话读取出指定的属性对象
public class UserAction {

    @Resource
    private UserBiz ub;

    @Resource
    private IndexAction ia;

    @RequestMapping("login")
    // @ResponseBody  // 返回 json ==> 页面跳转不能加 @ResponseBody
    public String login(@Valid User u, Errors errors, Model model,
                        // 用户输入的验证码
                        @RequestParam(required = false) String rcode,
                        // 会话中保存的验证码, 通过session.setAttribute写入的属性,
                        // 不能通过 @SessionAttribute 获取到
                        // @SessionAttribute(required = false) String vcode,
                        HttpSession session) {
        String vcode = (String) session.getAttribute("vcode");
        if (rcode == null || rcode.equalsIgnoreCase(vcode) == false) {
            errors.reject("vcodeError", "验证码输入错误!");
        }

        User user = null;
        try {
            user = ub.login(u, errors);
        } catch (BizException e) {
            model.addAttribute("errors", e.getErrors()); // getErrors ==> Object
            return "login";
        }
        // 将用户对象存入数据模型
        model.addAttribute("loginedUser", user);
        /**
         * 默认跳转: 请求转发 ==> 内部跳转 ==> 地址栏不变
         * 解决跳转到首页右边栏目无数据的问题
         * 1. 响应重定向
         * 2. 请求转发到其它控制器 : ia.index();
         * 3. 在该方法中再查一次
         */
        return "redirect:/";
    }

    /**
     * 用于打开 template 下指定页面
     * @param page
     * @return
     */
    @GetMapping("to{page}")
    public String toPage(@PathVariable String page) {
        return page;
    }

    @GetMapping("vcode")
    public void vcode(HttpServletResponse response, HttpSession session) throws IOException {
        String vcode = VerifyCodeUtils.outputImage(response);
        // 最终存入会话中
        session.setAttribute("vcode", vcode);
    }

    @Resource
    MailServiceImpl msi;

    /**
     * 发送邮件验证码
     */
    @GetMapping("sendRegEmail")
    @ResponseBody
    public Result sendRegEmail(String email, Model model, HttpSession session) {
        // 生成验证码
        String regVcode = "" + System.currentTimeMillis();
        regVcode = regVcode.substring(regVcode.length() - 4);
        // 写入会话
        model.addAttribute("regVcode", regVcode);
        // 发送邮件
        msi.sendSimpleMail(email, "注册用户验证码", "您的验证码是:" + regVcode + ", 请在15分钟之内完成注册!");
        return new Result(1, "发送成功", null);
    }

    @PostMapping("reg")
    public String reg(@Valid User u, Errors errors, Model model,
                      @RequestParam(required = false) String inputRegVcode,
                      @SessionAttribute(required = false) String regVcode) {
        if (inputRegVcode == null || inputRegVcode.equalsIgnoreCase(regVcode) == false) {
            errors.reject("regVcodeError","邮件验证码错误");
        }

        try {
            ub.register(u,errors);
            return "redirect:tologin";
        } catch (BizException e) {
            e.printStackTrace();
            model.addAttribute("errors",e.getErrors());
            return "reg.html";
        }

    }

    @Value("${headPath}")
    private String headPath;

    @PostMapping("upload")
    @ResponseBody
    public Result upload(MultipartFile head){
        String diskpath = headPath + "/" + head.getOriginalFilename();
        String webpath = "/" + head.getOriginalFilename();
        try {
            head.transferTo(new File(diskpath));
            return new Result(1, "头像上传成功", webpath);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(0, "头像上传失败", e.getMessage());
        }
    }

    /**
     *  重置密码
     *  1. 用户点击充值密码的连接, 打开重置密码页面
     *  2. 在页面中填写用户名(唯一)
     *  3. 根据用户名查找该用户账号, 如果找到, 则向账号中的邮箱地址发送验证码邮件
     *  4. 用户提交 验证码 + 新密码, 修改密码(重置)
     *  5. 完成
     */

}
